<?php

/*
 * 2007-2011 PrestaShop 
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author PrestaShop SA <contact@prestashop.com>
 *  @copyright  2007-2011 PrestaShop SA
 *  @version  Release: $Revision: 6882 $
 *  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */




if (!defined('_CAN_LOAD_FILES_'))
    exit;

class Discoicons extends Module {

    private $_html;

    public function __construct() {
        $this->name = 'discoicons';
        $this->tab = 'front_office_features';
        $this->version = 0.1;
        $this->author = 'gpaltan';
        $this->need_instance = 0;

        parent::__construct();

        $this->displayName = $this->l('Disco Icons');
        $this->description = $this->l('Set Icons:');

        if (!$this->isRegisteredInHook('header'))
            $this->registerHook('header');
    }

    public function install() {
        if (!parent::install() OR
                !$this->registerHook('productFooter') OR
                !$this->registerHook('header') OR
                !Configuration::updateValue('CROSSSELLING_DISPLAY_PRICE', 0) OR
                !Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'discoicons` (
  `productid` int(11) NOT NULL,
  `iconname` varchar(100) DEFAULT NULL,
  `moduleiconname` varchar(100) DEFAULT NULL,
   PRIMARY KEY (`productid`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8'))
            return false;
        return true;
    }

    public function uninstall() {
        if (!parent::uninstall() OR
                !Configuration::deleteByName('CROSSSELLING_DISPLAY_PRICE'))
            return false;
        return true;
    }

    public function getContent() {
        $no_of_products = 1;

        global $smarty, $cookie, $link;

        $this->_html = '<link type="text/css" href="' . ($this->_path) . 'jquery.ui.all.css" rel="stylesheet" />
	<link type="text/css" href="' . ($this->_path) . 'jquery.ui.selectmenu.css" rel="stylesheet" />
            <script type="text/javascript" src="' . ($this->_path) . 'jquery-1.5.1.js"></script>
        <script type="text/javascript" src="' . ($this->_path) . 'jquery.ui.widget.js"></script>
<script type="text/javascript" src="' . ($this->_path) . 'jquery.ui.core.js"></script>
<script type="text/javascript" src="' . ($this->_path) . 'jquery.ui.position.js"></script>
    <script type="text/javascript" src="' . ($this->_path) . 'jquery.ui.selectmenu.js"></script>
        <style type="text/css">
		/* demo styles */
		body {font-size: 62.5%; font-family:"Verdana",sans-serif; }
		fieldset { border:0; }	
		label,select,.ui-select-menu { float: left; margin-right: 10px; }
		select { width: 200px; }
		.ui-selectmenu-menu li a, .ui-selectmenu-status { padding: 0.3em 2em; }
					
		/* select with custom icons */
		body a.customicons { height: 2.8em;}
		body .customicons li a, body a.customicons span.ui-selectmenu-status { line-height: 2em; padding-left: 30px !important; }
		body .video .ui-selectmenu-item-icon, body .podcast .ui-selectmenu-item-icon, body .rss .ui-selectmenu-item-icon { height: 24px; width: 24px; }
		body .video .ui-selectmenu-item-icon { background: url(images/24-video-square.png) 0 0 no-repeat; }
		body .podcast .ui-selectmenu-item-icon { background: url(images/24-podcast-square.png) 0 0 no-repeat; }
		body .rss .ui-selectmenu-item-icon { background: url(images/24-rss-square.png) 0 0 no-repeat; }
		
		
	</style>
<style>
    #rounded-corner {
        font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        font-size: 12px;
        width: 480px;
        text-align: left;
        border-collapse: collapse;
        margin: 20px;
    }
    table {
        display: table;
        border-collapse: separate;
        border-spacing: 2px;
        border-color: gray;
    }
    #rounded-corner thead th.rounded-productid {
        background: #B9C9FE url("image/left.png") left -1px no-repeat;
    }
    #rounded-corner thead th.rounded-name {
        background: #B9C9FE url("image/left.png") left -1px no-repeat;
    }
    #rounded-corner td {
        background: #E8EDFF;
        border-top: 1px solid white;
        color: #669;
        padding: 8px;
    }
    #rounded-corner tbody tr:hover td {
        background: #D0DAFD;
    }
    #rounded-corner th {
        font-weight: normal;
        font-size: 13px;
        color: #039;
        background: #B9C9FE;
        padding: 8px;
    }
    .crs1{
        width: 200px;
    }
    option { 
        background: transparent url(../modules/discoicons/logo.gif) no-repeat 0% 0%; 
        padding-left:15px; 
        margin-top:4px; 
    } 

</style>
<script>
var prodids = new Array();
var selprodids = new Array();
var selp=new Array();
var i=0;
var j=0;
var k=-1;
$(document).ready(function(){  


$("select.crsm").selectmenu({
                                style:"popup", 
				icons: [
					{find: ".avatar"}
				],
				bgImage: function() {
					return "url(" + $(this).attr("title") + ")";
				},
                                menuWidth: "200px",
                                menuHeight: "15px"
			});

 $("form#submit").submit(function() {  
 
$("tr.crs").each(function(index) {


$(this).children("td.crsid").each(function(index1) {
            prodids[i++]=$(this).text();
            j=0;
            k++;
            //alert(index1+" id "+$(this).text());
});


$(this).find("select").each(function(index2) {
if(j==0)
{
    selprodids[k]=new Array();
}
            selprodids[k][j++]=$(this).val();
            //alert(index2+" sel: "+$(this).val());
});

        });


$.post("../modules/discoicons/csajax.php", { "prodids":prodids,"selprodids":selprodids},function(data) {

                       // Testing purpose
			//alert(data);
										
			}, "json");
                        
i=0;
j=0;
k=-1;

$("div.success").show(10);
$("div.success").fadeOut(5000);
        
return false;


    
    });
    


});
</script>';


        $disco = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('

		SELECT *
                FROM ' . _DB_PREFIX_ . 'discoicons ORDER BY productid ASC');


        $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('

		SELECT *
                FROM ' . _DB_PREFIX_ . 'product p
                LEFT JOIN ' . _DB_PREFIX_ . 'product_lang l ON (p.id_product = l.id_product)
		WHERE l.id_lang=1');

        $_select = $_select . '<option value="0">----------</option>';
        for ($index = count($products) - 1; $index >= 0; $index--) {
            $productids[$index] = $products[$index]['id_product'];
            $productnamess[$index] = $products[$index]['name'];
            $produ = new Product($productids[$index], true, (int) $cookie->id_lang);
            $images = $produ->getImages((int) $cookie->id_lang);
            $i = $link->getImageLink('', $productids[$index] . '-' . $images[0]['id_image'], "small");
            $_select = $_select . '<option class="avatar" title="' . $link->getImageLink('', $productids[$index] . '-' . $images[0]['id_image'], "small") . '" value="' . $products[$index]['id_product'] . '">' . $products[$index]['id_product'] . ' ' . $products[$index]['name'] . '</option>';
        }




        $this->_html = $this->_html . '<div><form id="submit" method="post">  <table id="rounded-corner">';
        $this->_html = $this->_html . '<thead><tr>
            <th scope="col" class="rounded-productid">Product id</th>
            <th scope="col" class="rounded-name">Thumbnail</th>
            <th scope="col" class="rounded-name">Name</th>';
        
            $this->_html = $this->_html . '<th scope="col" class="rounded-name">Icon</th>';
            $this->_html = $this->_html . '<th scope="col" class="rounded-name">Column Modules Icon</th>';
        $this->_html = $this->_html . '</tr></thead><tbody>';
        for ($index = count($products) - 1; $index >= 0; $index--) {
            $this->_html = $this->_html . '<tr class="crs">';
            $pidid=$products[$index]['id_product'];
            $produ = new Product($products[$index]['id_product'], true, (int) $cookie->id_lang);
            $images = $produ->getImages((int) $cookie->id_lang);
            $img = $link->getImageLink('', $products[$index]['id_product'] . '-' . $images[0]['id_image'], "small");
                   
            $this->_html = $this->_html . '<td class="crsid">' . $products[$index]['id_product'] . '</td>'. '<td class="crs"><img src="'. $img .'"/></td>'. '<td class="crs">' . $products[$index]['name'] . '</td>';
            
            

                $_select = '<option value="0">----------</option>';
                 
                $handle = opendir ('./../modules/discoicons/icons/');
                $files = array();



if ($handle = opendir ('./../modules/discoicons/icons/')) {

 while (false !== ($file = readdir($handle))) { 

if ($file != "." OR $file != ".."){

             $files[] = $file;

         }

 }

 closedir($handle); 

}



asort($files);




        	foreach ($files as $file) {
        		if($file != "." && $file != ".." && $file != basename(__FILE__)) {
            		
                		$_select = $_select . '<option ';
                		//$this->_html = $this->_html . '<img width="50" height="50" src="./../modules/discoicons/icons/'.$file.'"/>'.$file.'';
                		if($disco[$index]['iconname']==$file)
                                {
                                    $_select = $_select . 'selected ';
                                }
                                $_select = $_select . 'class="avatar" title="'.($this->_path).'/icons/'.$file.'" value="' . $file . '">' . $file . '</option>';
                        }
            		
       		}
                
                /*for ($ind = count($products) - 1; $ind >= 0; $ind--) {
                    $productids[$ind] = $products[$ind]['id_product'];
                    $productnamess[$ind] = $products[$ind]['name'];
                    $produ = new Product($productids[$ind], true, (int) $cookie->id_lang);
                    $images = $produ->getImages((int) $cookie->id_lang);
                    $img = $link->getImageLink('', $productids[$ind] . '-' . $images[0]['id_image'], "small");
                    $_select = $_select . '<option ';
                    $ttt=$buywithproducts[$index]['product'.$i];
                    $rrr=$buywithproducts[$index];
                    if($buywithproducts[$index]['product'.$i]==$products[$ind]['id_product'])
                    {
                        $_select = $_select . 'selected ';
                    }
                    $_select = $_select . 'class="avatar" title="' . $link->getImageLink('', $productids[$ind] . '-' . $images[0]['id_image'], "small") . '" value="' . $products[$ind]['id_product'] . '">' . $products[$ind]['id_product'] . ' ' . $products[$ind]['name'] . '</option>';
                }*/
                
                $this->_html = $this->_html . '<td class="crs"><select id="selproduct' . $i . '" class="crsm">' . $_select . '</select></td>';
            
                
                
                //2nd left column
                               $_select = '<option value="0">----------</option>';
                 
                $handle = opendir ('./../modules/discoicons/moduleicons/');
                $files = array();



if ($handle = opendir ('./../modules/discoicons/moduleicons/')) {

 while (false !== ($file = readdir($handle))) { 

if ($file != "." OR $file != ".."){

             $files[] = $file;

         }

 }

 closedir($handle); 

}



asort($files);




        	foreach ($files as $file) {
        		if($file != "." && $file != ".." && $file != basename(__FILE__)) {
            		
                		$_select = $_select . '<option ';
                		//$this->_html = $this->_html . '<img width="50" height="50" src="./../modules/discoicons/icons/'.$file.'"/>'.$file.'';
                		if($disco[$index]['moduleiconname']==$file)
                                {
                                    $_select = $_select . 'selected ';
                                }
                                $_select = $_select . 'class="avatar" title="'.($this->_path).'/icons/'.$file.'" value="' . $file . '">' . $file . '</option>';
                        }
            		
       		}
                
                /*for ($ind = count($products) - 1; $ind >= 0; $ind--) {
                    $productids[$ind] = $products[$ind]['id_product'];
                    $productnamess[$ind] = $products[$ind]['name'];
                    $produ = new Product($productids[$ind], true, (int) $cookie->id_lang);
                    $images = $produ->getImages((int) $cookie->id_lang);
                    $img = $link->getImageLink('', $productids[$ind] . '-' . $images[0]['id_image'], "small");
                    $_select = $_select . '<option ';
                    $ttt=$buywithproducts[$index]['product'.$i];
                    $rrr=$buywithproducts[$index];
                    if($buywithproducts[$index]['product'.$i]==$products[$ind]['id_product'])
                    {
                        $_select = $_select . 'selected ';
                    }
                    $_select = $_select . 'class="avatar" title="' . $link->getImageLink('', $productids[$ind] . '-' . $images[0]['id_image'], "small") . '" value="' . $products[$ind]['id_product'] . '">' . $products[$ind]['id_product'] . ' ' . $products[$ind]['name'] . '</option>';
                }*/
                
                $this->_html = $this->_html . '<td class="crs"><select id="selproduct1" class="crsm">' . $_select . '</select></td>';
            
                
                //end 2nd left column
                
                

            $this->_html = $this->_html . '</tr>';
        }
        $this->_html = $this->_html . '</tbody></table><button class="button positive"> Update </button> </form> ';
        /*$handle = opendir ('./../modules/discoicons/icons/');
        	while (false !== ($file = readdir($handle))) {
            		if($file != "." && $file != ".." && $file != basename(__FILE__)) {
                		$this->_html = $this->_html . '<img width="50" height="50" src="./../modules/discoicons/icons/'.$file.'"/>'.$file.'';
            		}
       		}*/
        $this->_html = $this->_html . '<div class="success" style="display: none;color:green">Updated Successfully...</div></div> ';
        return $this->_html;
    }

    public function hookHeader() {
        Tools::addCSS(($this->_path) . 'crossselling.css', 'all');
    }

    /**
     * Returns module content for left column
     */
    public function hookProductFooter($params) {
        global $smarty, $cookie, $link;
        //                    select * from '._DB_PREFIX_.'product_lang where id_lang=1');


        global $smarty;
        $current_product_id = ($params['product']->id);

        $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('

		SELECT *
                FROM ' . _DB_PREFIX_ . 'crosssellingbuywith p
                WHERE p.id=' . $current_product_id);
        $p = array();
        foreach ($products as $prod) {
            if (is_array($prod)) {
                $index = 0;
                for ($i = 1; $i < count($prod); $i++) {
                    $k = 'product' . $i;
                    $j = $prod[$k];
                    if ($j != 0) {
                        $pr = new Product($j, true, (int) $cookie->id_lang);
                        $cover = Product::getCover($j);
                        $pr->id_image = $j . '-' . $cover['id_image'];
                        $p[] = $pr;
                        $index = $index + 1;
                    }
                }
            }
        }

        $defaultLanguageId = (int) (Configuration::get('PS_LANG_DEFAULT'));
        $temp = $p[0]->link_rewrite;



        $smarty->assign(array(
            'products' => $p)
        );

        return $this->display(__FILE__, 'discoicons.tpl');
    }

}
